<template>
  <el-dialog title="修改密码" :visible.sync="dialogVisible" :close-on-click-modal="false"
             :close-on-press-escape="false" :before-close="handleClose" @close="$emit('update:visible',false)"
             top="100px" width="650px">
    <el-form :model="loginForm" label-width="80px" ref="editForm">
      <el-row>
        <el-col :span="22">
          <el-form-item label="旧密码" prop="name">
          <el-input
              v-model="loginForm.oldpassword"
              type="text"
              name="pwd"
              id="pwd"
              placeholder="密码"
              autocomplete="off"
              @input="setPassword($event, 'oldpassword')">
              <i slot="suffix" class="el-icon-view" @click="hidePassword('oldpassword')"></i>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
          <el-form-item label="新密码" prop="name">
           <el-input
              v-model="loginForm.password"
              type="text"
              name="pwd"
              id="pwd"
              placeholder="新密码（密码长度需大于8位数，包含数字、大小写字母、特殊字符）"
              autocomplete="off"
              @input="setPassword($event, 'password')">
              <i slot="suffix" class="el-icon-view" @click="hidePassword('password')"></i>
            </el-input>
            <div class="password_strong">
              <div class="input_span">
                <span
                  :style="{'background-color':(msgText > 1 || msgText == 1) ?  '#FC5F76' : '#BBBBBB', 'color': (msgText > 1 || msgText == 1) ?  '#FC5F76' : '#BBBBBB' }">弱</span>
                <span
                  :style="{'background-color':(msgText > 2 || msgText == 2) ?  '#FF9900' : '#BBBBBB', 'color': (msgText > 2 || msgText == 2) ?  '#FF9900' : '#BBBBBB'}">中</span>
                <span
                  :style="{'background-color':(msgText > 4 || msgText == 4) ?  '#33CC00' : '#BBBBBB', 'color': (msgText > 4 || msgText == 4) ?  '#33CC00' : '#BBBBBB'}">强</span>
              </div>
              长度需大于8位数、包含数字、大小写字母、特殊字符
            </div>

          </el-form-item>
        </el-col>
        <el-col :span="2">
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
          <el-form-item label="重复密码" prop="name">
         <el-input
              v-model="loginForm.repassword"
              type="text"
              name="pwd"
              id="pwd"
              placeholder="重复密码"
              autocomplete="off"
              @input="setPassword($event, 'repassword')">
              <i slot="suffix" class="el-icon-view" @click="hidePassword('repassword')"></i>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click.native="resetForm" size="small">取消</el-button>
      <el-button type="primary" @click.native="editSubmit" size="small">提交</el-button>
    </div>
  </el-dialog>
</template>
<script>

export default {
  name: 'Dialog',
  props: ['visible'],
  watch: {
    visible() {
      this.dialogVisible = this.visible
    },
    password() {
      console.log('oldpassword:', this.password)
      this.msgText = this.checkStrong(this.password);
    }
  },
  data() {
    return {
      tieleName: '',
      dialogVisible: false,
      loginForm: {
        password: '',
        oldpassword: '',
        repassword: ''
      }, // 编辑界面数据
      password: '',
      oldpassword: '',
      repassword: '',
      isShowPassword_password: false,
      isShowPassword_oldpassword: false,
      isShowPassword_repassword: false,
      msgText: "",
    }
  },

  created() {
  },
  methods: {
    // 密码强度
    checkStrong(sValue) {
      let modes = 0;
      //正则表达式验证符合要求的
      if (sValue.length < 1) return modes;
      if (/\d/.test(sValue)) modes++; //数字
      if (/[a-z]/.test(sValue)) modes++; //小写
      if (/[A-Z]/.test(sValue)) modes++; //大写
      if (/\W/.test(sValue)) modes++; //特殊字符
      console.log('特殊自负:', modes)
      //逻辑处理
      switch (modes) {
        case 1:
          return 1;
          break;
        case 2:
          if(sValue.length<4){
            return 1;
          }else{
            return 2;
          }
          break;
        case 3:
          if(sValue.length<5){
            return 1;
          }else{
            return 2;
          }
          break;
        case 4:
          return sValue.length <= 8 ? 3 : 4;
          break;
      }
      return modes;
    },
    setPassword(val, key) {
      if (this[`isShowPassword_${key}`]) {
        this.loginForm[key] = val;
        this[key] = val;
      } else {
        let nDot = /[^●]/g; // 非圆点字符
        let index = -1; // 新输入的字符位置
        let lastChar = void 0; // 新输入的字符
        let realArr = this[key].split(""); // 真实密码数组
        let coverArr = val.split(""); // 文本框显示密码数组
        let coverLen = val.length; // 文本框字符串长度
        let realLen = this[key].length; // 真实密码长度
        // 找到新输入的字符及位置
        coverArr.forEach((el, idx) => {
          if (nDot.test(el)) {
            index = idx;
            lastChar = el;
          }
        });
        if (coverLen - 1 !== realLen) {
          // 一进入长度判断是否复制
          // 其中会发生如果先输入，后复制会有前面数字为圆点
          realArr = coverArr
        } else {
          if (realLen < coverLen) {
            // 新增字符
            realArr.splice(index, 0, lastChar);
          } else if (coverLen <= realLen && index !== -1) {
            // 替换字符（选取一个或多个字符直接替换）
            realArr.splice(index, realLen - (coverLen - 1), lastChar);
          } else {
            // 删除字符，因为 val 全是 ● ，没有办法匹配，不知道是从末尾还是中间删除的字符，删除了几个，不好对 password 处理，所以可以通过光标的位置和 val 的长度来判断
            let pos = document.getElementById("pwd").selectionEnd; // 获取光标位置
            realArr.splice(pos, realLen - coverLen);
          }
        }
        // 将 pwdCover 替换成 ●
        this.loginForm[key] = val.replace(/\S/g, "●");
        this[key] = realArr.join("");
      }
    },
    // 点击右侧小眼睛控制显示隐藏
    hidePassword(key) {
      if (!this[`isShowPassword_${key}`]) {
        // console.log("显示");
        this[`isShowPassword_${key}`] = true;
        this.loginForm[key] = this[key];
      } else {
        // console.log("隐藏");
        this[`isShowPassword_${key}`] = false;
        this.loginForm[key] = this.loginForm[key].replace(/\S/g, "●");
      }
    },
    handleClose() {
      this.dialogVisible = false
    },
    resetForm() {
      this.dialogVisible = false
    },
    editSubmit() {

      let passData_ = JSON.parse(JSON.stringify(this.loginForm))
      if (!passData_.oldpassword) {
        this.$message.error('请输入旧密码')
        return
      }
      if (!passData_.password) {
        this.$message.error('请输入新密码')
        return
      }
      if(this.msgText<3){
        this.$message.error('长度需大于8位数、包含数字、大小写字母、特殊字符')
        return
      }
      if (!passData_.repassword) {
        this.$message.error('请输入重复密码')
        return
      }
      if (this.password !== this.repassword) {
        this.$message.error('两次密码输入不一致')
        return
      }
      passData_.password = this.password
      passData_.oldpassword = this.oldpassword
      passData_.repassword = this.repassword
      this.$post(this.api.password_setting, passData_).then((response) => {
        if (response.code === 0) {
          this.$message({
            message: '设置成功',
            type: 'success'
          })
          this.dialogVisible = false
        } else {
          this.$message.error(response.msg)
        }
      }).catch((err) => {
        console.log(err)
      })
    }
  }
}
</script>
<style>
.password_strong{
  display: flex;
  align-items: center;
  font-size: 12px;
  justify-content: space-between;
  color: #777;
}
.input_span {
  height: 8px;
  display: flex;
  width: 35%;
}

.input_span span {
  display: inline-block;
  width: 30%;
  border-radius: 8px;
  margin-right: 3px;
  text-align: center;
  margin-top: 3px;
}
</style>
